<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');
require_once(Settings::getHome().'/classes/template.php');
require_once(Settings::getHome().'/classes/tutorial.php');

//Load Tutorial
if(isset($_GET['name'])) {
    try {
        $tutorial = new Tutorial($_GET['name']);
    }
    catch(Exception $e) {
        Template::render404();
    }
}
else {
    Template::render404();
}

//Set Current Article
if(isset($_GET['current'])) {
    try {
        $tutorial->moveTo($_GET['current']);
    }
    catch(Exception $e) {
        header('Location:/tutoriales/'.$_GET['name']);
    }
}

//Get Previous and Next Links
$previous = $next = '';
if($toc = $tutorial->getTOC()) {
    $toc = DOMDocument::loadXML($toc);
    $items = $toc->getElementsByTagName('a');
    for ($i = 0; $i < $items->length; $i++) {
        if(strpos($items->item($i)->parentNode->getAttribute('class'),'current')!==false)
            $currentIndex = $i;
    }
    if($currentIndex>0)
        $previous = '<a href="'.$items->item($currentIndex-1)->getAttribute('href').'
                    ">&lt;&lt; Anterior</a>';
    if($currentIndex< $items->length-1)
        $next = '<a href="'.$items->item($currentIndex+1)->getAttribute('href').'
                    ">Siguiente &gt;&gt;</a>';
}

//Render page
$content = Template::renderStatic('/templates/tutoriales.xhtml', 
        array(
            '#TOC#'=>$tutorial->getTOC(),
            '#TUTORIAL#'=>$tutorial->getCurrentContent(),
            '#PREV#'=>$previous,
            '#NEXT#'=>$next,
        )
    );

$page = new Template('/templates/layout.xhtml', 
        array(
            '#TITLE#'=>$tutorial->getCurrentTitle(),
            '#CSS#' => '<link href="/css/tutoriales.css" rel="stylesheet" type="text/css" />',
            '#CONTENT#' => $content
        )
    );
if(strpos($_SERVER['REQUEST_URI'],'/tutoriales/unirTrisfera')!==false) {
    $page->addValue('#MENU_UNIRME#','class="current"');
}
require(Settings::getHome().'/includes/mimetype.php');
echo $page->render();
?>
